import Vue from 'vue';
import axios from 'axios';
import qs from 'qs';
import {
    Loading,
    MessageBox
} from 'element-ui';

axios.defaults.timeout = 10000;
axios.defaults.baseURL = '';
// axios.defaults.baseURL = 'http://47.92.123.194:8030/';
let loading;
// loading.close();
//http request 拦截器
axios.interceptors.request.use(
    config => {
        loading = Loading.service({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(255, 255, 255, 0.7)'
        });
        config.headers = {
            'Content-Type': config.data.ifQs ? 'multipart/form-data' : 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-requested-width': 'XMLHttpRequest',
        }
        if (!config.data.ifQs) {
            config.data = qs.stringify(config.data);
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//http response 拦截器
axios.interceptors.response.use(
    response => {
        loading.close();
        if (response.data.status != 1) {
            MessageBox(response.data.msg, '', {
                confirmButtonText: '确定',
            });
            return
        }
        return response;
    },
    error => {
        return Promise.reject(error)
    }
)

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
                params: params
            })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}, ifQs = false) {
    data.ifQs = ifQs
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then(response => {
                if (response != undefined) {
                    resolve(response.data);
                }
            }, err => {
                console.log(1)
                reject(err)
            })
    })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.patch(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.put(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}